// import Select from '../../../_antd1.11.2/Select';
// import Input from '../../../_antd1.11.2/Input';
// import Button from '../../../_antd1.11.2/Button';
// import Icon from '../../../_antd1.11.2/Icon';
import {Select, Input, Button, Icon} from 'antd';
import classNames from 'classnames';
import WeaTools from '../../wea-tools'
import forEach from 'lodash/forEach'
import isEmpty from 'lodash/isEmpty'
import debounce from 'lodash/debounce'
import trim from 'lodash/trim'
import isString from 'lodash/isString'
const Option = Select.Option;
import PureRenderMixin from 'react-addons-pure-render-mixin';

class main extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data: [],
            value: [],
            loading: false,
            focus: false,
            dropdownWidth: 200,
            activeKey: '',
        };
    }
    // 根据ids 更新组件
    updateByIds(ids, names) {
        const {type} = this.props;
        if (!isEmpty(ids) && !isEmpty(names)) {
            this.setState({data:[{id: ids, name: names}] , value: [ids]});
        } else {
            this.setState({data: [], value: []});
        }
    }
    componentDidMount(){
        const {dropdownWidth} = this.state;
        this.updateByIds(this.props.ids, this.props.names);
        const w = $(this.refs.searchWrapper).outerWidth();
        if (dropdownWidth < w) {
            this.setState({dropdownWidth: w});
        }
    }
    componentWillReceiveProps(nextProps, nextState){
        if (this.props.ids !== nextProps.ids && nextProps.ids) {
            this.updateByIds(nextProps.ids, nextProps.names);
        }
        if (this.props.defaultFocus !== nextProps.defaultFocus && nextProps.defaultFocus) {
            this.setState({focus: true});
        }
        this.props.isClearData !== nextProps.isClearData && this.forceClear();
    }
    componentDidUpdate() {
        const dom = this.refs.searchWrapper;
        if (this.state.focus) {
            $(dom).find('.ant-select-search--inline').css('minWidth', '10px');
            $(dom).find('input').focus();
        } else {
            $(dom).find('.ant-select-search--inline').css('minWidth', '0px');
        }
    }
    shouldComponentUpdate(...args) {
        return PureRenderMixin.shouldComponentUpdate.apply(this, args);
    }
    // shouldComponentUpdate(nextProps,nextState) {
    //     return this.props.style !== nextProps.style
    //         || this.props.isClearData !== nextProps.isClearData
    //         || this.props.modalVisable !== nextProps.modalVisable
    //         || this.props.ids !== nextProps.ids
    //         || this.props.names !== nextProps.names
    //         || this.props.inputId !== nextProps.inputId
    //         || this.props.type !== nextProps.type
    //         || this.props.viewAttr !== nextProps.viewAttr
    //         || this.props.defaultFocus !== nextProps.defaultFocus
    //         || this.state.loading !== nextState.loading
    //         || this.state.value !== nextState.value
    //         || this.state.data !== nextState.data
    //         || this.state.loading !== nextState.loading;
    // }
    forceClear() {
        this.setState({data: [], value:[]});
    }
    getData(name = '') {
        let {type, oldUrl, completeURL} = this.props;
        const {value} = this.state;
        type = type || 1;
        let data = [];
        if (value.length > 0) {
            let name = this.getNameById(value[0]);
            data = [{id: value[0], name: name}]
        }
        let url = completeURL || `/api/workflow/browser01/complete/${type}?`;
        if (oldUrl) {
            url = `/api/ec/api/data/search?type=${type}&`
        }
        if (trim(name)) {
            const {type} = this.props;
            WeaTools.callApi(`${url}q=${encodeURIComponent(trim(name))}`,'GET').then((res)=> {
                let resD = isString(res.datas) &&　res.datas.length > 0? JSON.parse(res.datas): res.datas;
                if (oldUrl) resD = res;
                resD = resD || [];
                data = data.concat(resD);
                this.setState({data: data, loading: false, activeKey: this.getActiveKey(data)});
            });
        } else {
            this.setState({data: data, loading: false, activeKey: this.getActiveKey(data)});
        }
    }
    handleBlur() {
        this.getData();
        this.setState({activeKey: ''});
    }
    handleFocus() {
        this.setState({focus: true});
    }
    getNameById(id) {
        const {data} = this.state;
        if (!isEmpty(data)) {
            for (let i = 0; i < data.length; i++) {
                if (id === data[i].id) {
                    return data[i].name;
                }
            }
        }
        return '';
    }
    updateValue(value) {
        if (this.props.onChange) {
            this.props.onChange(value || '', this.getNameById(value));
        }
    }
    // 处理单选
    handleSelect(value) {
        let name = this.getNameById(value);
        this.setState({value: [value], data:[{id: value, name: name}], activeKey: ''});
        this.updateValue(value);
    }
    // 是否是人力浏览按钮
    isCrm() {
        const type = this.props.type || 1;
        return type === 1 || type === 17 || type === '1' || type === '17';
    }
    //只读
    isReadOnly() {
        const {viewAttr} = this.props;
        return viewAttr === 1 || viewAttr === '1';
    }
    //处理点击
    selectedClickHandler(e) {
        let item = this.state.data[0];
        if (this.isCrm()) {
            window.openhrm(item.id);
            window.pointerXY(e.nativeEvent);
        } else {
            const {linkUrl, inputId} = this.props;
            if (linkUrl) {
                let url = `${linkUrl}${item[inputId] || item.id}`
                window.open(url);
            }
        }
    }
    // 处理单选
    handleDeselect(value) {
        this.setState({value: [],data:[], activeKey: ''});
        this.updateValue();
    }
    handleSearch(value) {
        this.setState({loading: true});
        this.getData(value);
    }
    handleClick() {
        if (this.props.clickCallback){
            this.props.clickCallback(this.state.data);
        }
    }
    getActiveKey(data) {
        let v = '';
        const {value} = this.state;
        if (data && data.length > 0) {
            v = data[0].id;
            if (!isEmpty(value)) {
                let target = data.filter((d) => d.id !== value[0]);
                if (!isEmpty(target)) v = target[0].id;
            }
        }
        return v;
    }
    addOnClick() {
        this.props.addOnClick && this.props.addOnClick();
    }
    render() {
        // console.log('this.props',(this.props.type==263 || this.props.type==58) && this.props);
        const {value, data, dropdownWidth, activeKey} = this.state;
        const {underline, fieldName, hasBorder, viewAttr, style = {}, tempTitle, cls, resize, isCity, linkUrl, isDetail, hasAddBtn, modalVisable, hasScroll, layout} = this.props;
        let clss = cls || '';
        style.textDecoration = 'none';
        const clsname = classNames({
            'required': viewAttr=='3' && isEmpty(value),
            'mr12': /^field/.test(fieldName) || (viewAttr=='3' && isEmpty(value)),
            'resize': resize,
            'wea-associative-click': this.isCrm() || !isEmpty(linkUrl),
            'ext-btn': hasAddBtn,
            'border': hasBorder,
            'underline': underline,
        });

        if (this.isReadOnly()) {
            return (
                <span id={`${this.props.fieldName}span`} className={`wea-associative-search wea-field-readonly ${clsname} ${clss}`} style={style} ref="searchWrapper">
                    {!isEmpty(value) && !isEmpty(data) && isString(data[0].name) &&
                        <a className="child-item cursor-pointer wdb"
                            onClick={(e) => this.selectedClickHandler(e)} dangerouslySetInnerHTML={{__html: data[0].name}}>
                        </a>
                    }
                    {!isEmpty(value) && !isEmpty(data) && !isString(data[0].name) &&
                        <a className="child-item cursor-pointer wdb"
                            onClick={(e) => this.selectedClickHandler(e)}>
                            {data[0].name}
                        </a>
                    }
                </span>
            )
        }
        let options = data.map(d => d.id && <Option title={d.title || d.name} key={d.id}>{d.name}</Option>)
        let select = <Select
                        fieldName={fieldName}
                        hasScroll={hasScroll}
                        onInputBlur={()=> {this.setState({focus: false})}}
                        title={tempTitle}
                        hideSelected={true}
                        transitionName=""
                        animation=""
                        value = {value}
                        multiple={true}
                        placeholder={this.props.placeholder}
                        notFoundContent=""
                        activeKey={activeKey}
                        defaultActiveFirstOption={true}
                        showArrow={false}
                        filterOption={false}
                        onSelect={this.handleSelect.bind(this)}
                        onBlur={this.handleBlur.bind(this)}
                        onFocus={this.handleFocus.bind(this)}
                        onDeselect={this.handleDeselect.bind(this)}
                        onSearch={debounce(this.handleSearch, 400).bind(this)}
                        selectedClose={true}
                        selectedClickCB={this.selectedClickHandler.bind(this)}
                        dropdownStyle={{minWidth: dropdownWidth}}
                        getPopupContainer={() => this.props.getPopupContainer && this.props.getPopupContainer() || layout ||this.refs.searchWrapper}
                    >
                        {options}
                    </Select>
        return (
            <div className={`wea-associative-search wea-associative-single ${clss} ${clsname}`} style={style} ref="searchWrapper">
                {select}
                <Icon type="loading" style={{display: this.state.loading ? 'block' : 'none'}} />
                <div className="ant-input-group-wrap">
                    {
                        !isCity ?
                        <Button type="ghost" icon="search" onClick={this.handleClick.bind(this)}/>
                        :<Button type="ghost" style={{'paddingTop': '4px'}} size="small" onClick={this.handleClick.bind(this)}>
                            <span>{modalVisable ?<i className='icon-coms-up'/> :<i className='icon-coms-down'/>}</span>
                        </Button>
                    }
                </div>
                {
                    hasAddBtn &&
                    <div className="ant-input-group-wrap extbtn">
                        <Icon className="add-icon" type="plus" onClick={this.addOnClick.bind(this)}/>
                    </div>
                }
            </div>
        )
    }
}
export default main;